package com.blue.http.config;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.Assert;

import com.blue.http.util.HttpException;

/**
 * 错误配置，单例
 * 
 * @author zhengj
 * @since 1.0 2016年11月13日
 */
public class ErrorConfig
{
	private static ErrorConfig instance = new ErrorConfig();

	private Map<Integer, String> cache = new HashMap<>();

	public static final int SUCCESS = 0;
	public static final int ERROR = 1;
	public static final int LOGIN = 2;
	public static final int TOKEN = 3;
	public static final int AUTH = 4;
	public static final int PARAM = 5;
	public static final int JSON = 6;
	public static final int NOT_FOUND = 7;
	public static final int MAX_UPLOAD = 8;
	public static final int NO_DATA = 9;
	public static final int SESSION = 10;
	public static final int BUSINESS = 11;
	public static final int ERROR_UPLOAD = 12;
	public static final int ERROR_VERIFY = 13;

	private ErrorConfig()
	{
		cache.put(SUCCESS, "成功");
		cache.put(ERROR, "系统错误");
		cache.put(LOGIN, "登录失败");
		cache.put(TOKEN, "无效令牌");
		cache.put(AUTH, "无访问权限");
		cache.put(PARAM, "参数不合法");
		cache.put(JSON, "JSON 格式错误");
		cache.put(NOT_FOUND, "找不到URL");
		cache.put(MAX_UPLOAD, "上传文件超出限制");
		cache.put(NO_DATA, "没有数据");
		cache.put(SESSION, "无效会话");
		cache.put(BUSINESS, "业务错误");
		cache.put(ERROR_UPLOAD, "上传文件错误");
		cache.put(ERROR_VERIFY, "验证码错误");
	}

	public static ErrorConfig getInstance()
	{
		return instance;
	}

	public HttpException getException(Integer code)
	{
		String message = cache.get(code);
		if (message == null)
			return null;

		return new HttpException(code, message);
	}

	public String get(Integer code)
	{
		return cache.get(code);
	}

	public void put(Integer code, String message)
	{
		Assert.notNull(code, "错误代码不能为空");
		Assert.notNull(message, "错误信息不能为空");
		cache.put(code, message);
	}
	
	public List<Error> allError()
	{
		List<Error> list = new ArrayList<>();
		cache.forEach((k, v) -> list.add(new Error(k, v)));
		Collections.sort(list);
		return list;
	}

	public static class Error implements Comparable<Error>
	{
		private Integer code;
		private String message;

		public Error(Integer code, String message)
		{
			this.code = code;
			this.message = message;
		}

		public Integer getCode()
		{
			return code;
		}

		public String getMessage()
		{
			return message;
		}

		@Override
		public int compareTo(Error o)
		{
			return code.compareTo(o.code);
		}

	}

}
